<?php
/**
 * 问答平台 队列
 * @Author: king
 * @Date:   2019-05-20 15:42:56
 * @Last Modified by:   king
 * @Last Modified time: 2019-06-09 16:49:08
 */
namespace App\Tools;

use App\Exceptions\ApiException;
use App\Models\Api\LanmeiCounselor;
use App\Models\Api\LanmeiCounselorGrabRecord;
use App\Models\Api\LanmeiCounselorProblem;
use App\Models\Api\LanmeiOrderRefund;
use App\Tools\Orders;
use Illuminate\Contracts\Queue\Job;

class ProblemAndAnswerJob
{
    /**
     * 待回答问题 ---> 结束->进入结算状态
     * @param Job $job
     * @param $data
     * @throws \ApiException
     * @throws \Exception
     */
    public function problemPaddingTask(Job $job, $data)
    {
        print('问题ID【' . $data['cp_id'] . '】待回答结束；进入结算开始：' . date('Y-m-d H:i:s') . PHP_EOL);
        $problemModel = new LanmeiCounselorProblem();
        $problemData  = $problemModel->getProblemInfoById($data['cp_id'], 'problem_status,answer_people,counselor_mode,id,problem_type,order_id');
        // 判断是否 是待回答状态
        if ($problemData['problem_status'] != 3) {
            // 如果不是 删除队列任务
            print('问题ID【' . $data['cp_id'] . '】问题不是待回答状态；队列删除：' . date('Y-m-d H:i:s') . PHP_EOL);
            $job->delete();
            return;
        }
        // 判断 是不是公开悬赏 如果是 判断问题池 数量是否有缺失（被抢答） 如果没有缺失则问题关闭
        if ($problemData['answer_people'] == 0) {
            // 如果问题没人回答
            if ($problemData['counselor_mode'] == 1// 指定
                 || ($problemData['counselor_mode'] == 2) && LanmeiCounselorGrabRecord::isPendingByProblem($data['cp_id'])) //公开 判断是否有用户抢答且待回答状态 如果没有则订单关闭
            {
                // 问题关闭 退款
                $problemModel->problemClosed($problemData['id'], $problemData['counselor_mode'], $problemData['problem_type'], $problemData['order_id']);
                print('问题ID【' . $data['cp_id'] . '】问题没有人回答；问题关闭完成：' . date('Y-m-d H:i:s') . PHP_EOL);
                $job->delete();
                return;
            }
        }
        // 问题进入待结算状态
        $problemModel->problemEnterSettlement($problemData['id'], $problemData['counselor_mode'], $problemData['problem_type']);
        // 创建结算队列
        $queueConfig = config('queue');
        queuePush($queueConfig['problem_success_task'], ['cp_id' => $problemData['id']], $queueConfig['problem_success_queue'], $queueConfig['problem_success_delay']);

        print('问题ID【' . $data['cp_id'] . '】待回答结束；进入结算完成：' . date('Y-m-d H:i:s') . PHP_EOL);
        $job->delete();
    }

    /**
     * 待结算问题 ---> 结算-->问题进行结算
     * @param Job $job
     * @param $data
     * @throws \Exception
     */
    public function problemSuccessTask(Job $job, $data)
    {
        print('问题ID【' . $data['cp_id'] . '】结算开始：' . date('Y-m-d H:i:s') . PHP_EOL);
        $problemModel = new LanmeiCounselorProblem();
        $problemData  = $problemModel->getProblemInfoById($data['cp_id']);
        // 判断是否 是待结算状态
        if ($problemData['problem_status'] != 4) {
            // 如果不是 说明已经结算过了 删除队列任务
            $job->delete();
            print('问题ID【' . $data['cp_id'] . '】不是待结算状态，问题关闭：' . date('Y-m-d H:i:s') . PHP_EOL);
            return;
        }

        $result = $problemModel->problemSuccess($problemData);
        if ($result) {
            print('问题ID【' . $data['cp_id'] . '】结算完成：' . date('Y-m-d H:i:s') . PHP_EOL);
            $job->delete();
        } else {
            print('问题ID【' . $data['cp_id'] . '】结算异常，60秒后重启队列：' . date('Y-m-d H:i:s') . PHP_EOL);
            $job->release(60);
        }
    }

    /**
     * 抢单 --> 30分钟倒计时 问题回收
     * @param Job $job
     * @param $data
     * @throws \Exception
     */
    public function grabProblem(Job $job, $data)
    {
        try
        {
            print('问题ID【' . $data['id'] . '】抢单；答题超时回收开始：' . date('Y-m-d H:i:s') . PHP_EOL);

            LanmeiCounselorGrabRecord::grabProblemCallBack($data['id']);

            print('问题ID【' . $data['id'] . '】抢单；答题超时回收完成：' . date('Y-m-d H:i:s') . PHP_EOL);
            $job->delete();
        } catch (Exception $e) {
            \Log::info('问题ID【' . $data['id'] . '】抢单；答题超时回收失败：' . $e->getMessage() . date('Y-m-d H:i:s') . PHP_EOL);
            $job->release(60);
        }
    }

    /**
     * 更新咨询师 星级 采纳率 信息队列
     * @param Job $job
     * @param $data
     * @throws \Exception
     */
    public function updateCounselorInfo(Job $job, $data)
    {
        $msgData = json_encode($data);
        print($msgData . '更新咨询师开始：' . date('Y-m-d H:i:s') . PHP_EOL);

        if (empty($data)) {
            print($msgData . '更新咨询师:参数异常-删除队列：' . date('Y-m-d H:i:s') . PHP_EOL);
            $job->delete();
        }

        try
        {
            // 星级评分及采纳率更新
            $result = (new LanmeiCounselor())->integralStatistics($data);

            if ($result) {
                print($msgData . '更新咨询师完成：' . date('Y-m-d H:i:s') . PHP_EOL);
                $job->delete();
            } else {
                \Log::info($msgData . '更新咨询师失败：一分钟后重新更新：' . date('Y-m-d H:i:s') . PHP_EOL);
                $job->release(60);
            }
        } catch (Exception $e) {
            \Log::info($msgData . '更新咨询师失败:' . $e->getMessage() . date('Y-m-d H:i:s') . PHP_EOL);
            $job->release(60);
        }
    }

    /**
     * 问题退款
     * @param Job $job
     * @param $data
     * @throws \Exception
     */
    public function problemRefund(Job $job, $data)
    {
        try
        {
            printf('单号【' . $data['refund_id'] . '】退款开始:' . date('Y-m-d H:i:s') . PHP_EOL);
            $refundInfo = (new LanmeiOrderRefund())->where('refund_id', $data['refund_id'])->first();

            if (empty($refundInfo) || $refundInfo['status'] != 1) {
                // 已经发起了退款
                printf('退款单号【' . $data['refund_id'] . '】不存在或已退款->退款队列关闭:' . date('Y-m-d H:i:s') . PHP_EOL);
                $job->delete();
                return;
            }

            switch ($refundInfo['type']) {
                case 1:
                    $refund_reason = '问答结算退款';
                    break;
                case 2:
                    $refund_reason = '答案举报退款';
                    break;
                default:
                    $refund_reason = '提问失败退款';
            }

            // 进行退款
            $result = Orders::orderRefund([
                'id'            => $refundInfo['id'],
                'refund_id'     => $refundInfo['refund_id'],
                'price'         => $refundInfo['price'],
                'order_id'      => $refundInfo['order_id'],
                'aid'           => $refundInfo['aid'],
                'refund_reason' => $refund_reason,
                'trade_type'    => $refundInfo['trade_type'],
            ]);

            if ($result) {
                printf('单号【' . $data['refund_id'] . '】退款成功:' . date('Y-m-d H:i:s') . PHP_EOL);
                $job->delete();
            } else {
                \Log::info('单号【' . $data['refund_id'] . '】退款失败 1分钟后重启' . date('Y-m-d H:i:s') . PHP_EOL);
                $job->release(60);
            }
        } catch (Exception $e) {
            $job->release(60);
            \Log::info('单号【' . $data['refund_id'] . '】退款失败:' . $e->getMessage() . date('Y-m-d H:i:s') . PHP_EOL);
        }
    }

    /**
     * 公开问题池-->丢失重建
     * @param Job $job
     * @param $data
     */
    public function openedProblemGrabIoc(Job $job, $data)
    {
        $job->delete();
    }
}
